import { ref } from "vue";
import { watch } from "vue";
import { useLayout } from "@/stores/layout";
import { BalanceHistory } from "./ChartConfig";
import { usePerson } from "@/stores/person";
import { Bus, CLEVER_CHART_SWITCH, CLEVER_TYPE_SWITCH, CONN_ACTIVITY } from "@/connetion/Bus";

/**按钮枚举 */
enum DownType {
    /**数据异动 */
    DataChanges,
    /**余额历史记录 */
    BalanceHistory
}
const lodding = ref(false);
/**nva按钮数据类型 */
interface BtnsType {
    label: string;
    value: string | null;
}

enum CTYPE {
    area = `<span class="iconfont icon-gupiao"></span>`,
    solid = `<span class="mdi mdi-chart-line"></span>`
    // solid = `<span class="iconfont icon-gupiao1"></span>`
}

/**时间nav按钮数据 */
const btnsData = [
    {
        label: "D",
        value: "D"
    },
    {
        label: "H",
        value: "H"
    },
    {
        label: CTYPE.solid,
        value: "line"
    }
];

class YTab {
    static list: any[] = [];
    static btns = ref<BtnsType[]>(btnsData);
    static idx = ref(YTab.btns.value[0]);
    static page = ref(DownType.DataChanges);
    static onTypeChange: (t: any) => void;
    static onnvadown: (val: number) => void;
    static resize: () => void;
    static initChat: () => void;
}

YTab.resize = () => {
    if (kfig) {
        kfig.figTab?.resize();
        setTimeout(() => {
            kfig?.figTab?.resize();
        }, 300);
    }
};
YTab.initChat = async () => {
    lodding.value = true;
    await capital.loadHistory();
    if (YTab.list && YTab.list.length) {
        Kfig.addBalanceHistory(YTab.list);
        console.log("重置");
    }
}
//6|10|15按钮切换
YTab.onTypeChange = function (t: any) {
    // console.log('yzt', t);
    // YTab.idx.value
    console.log(YTab.idx);
    Bus.emit(CLEVER_TYPE_SWITCH, t);

    if (t.value == "line") {
        YTab.btns.value[2].label = t.label == CTYPE.area ? CTYPE.solid : CTYPE.area;
    }
};
//数据异动 and 余额历史记录 监听
YTab.onnvadown = async function (val: number) {
    YTab.page.value = val;
    switch (val) {
        case DownType.DataChanges:
            Bus.emit(CLEVER_CHART_SWITCH);
            break;
        case DownType.BalanceHistory:
            lodding.value = true;
            await capital.loadHistory();
            if (YTab.list && YTab.list.length) {
                Kfig.addBalanceHistory(YTab.list);
                console.log("重置");
            }
            break;
    }
};

//---------以下是图表数据生成操作------
let kfig: Kfig | undefined;

//监听图表大小变化
watch(
    () => useLayout().newsOpen,
    () => {
        setTimeout(() => {
            kfig?.figTab?.resize();
        }, 200);
    }
);
const capital = usePerson();
//监听
watch(
    () => capital.detail,
    (newVal: any, oldVal: any) => {
        console.log("capital.blockBalanceList", capital.curblockBalance);
        // console.log('yzt', newVal);
        // if (YTab.page.value === DownType.BalanceHistory) {
        // console.log('yzt历史数据');
        // Kfig.addBalanceHistory(newVal.contractAddress);
        // }
        // curItem.value = newVal[0];
        // console.log('yzt下拉数据变化', newVal[0]);
    }
);

watch(
    () => capital.historyAmount,
    (newVal: any, oldVal: any) => {
        // console.log("historyAmount##############", newVal);
        lodding.value = false;
        Kfig.addBalanceHistory(newVal);
    }
);
interface DayData {
    timestamp: number;
    position: Position[];
}

interface Position {
    // contractAddress: string;
    symbol: string;
    usd: number;
    balance: number;
    timestamp: number;
}
class Kfig {
    static addBalance: { name: string; token: string } | undefined;
    figTab: echarts.ECharts | undefined;
    //初始化数据表div元素对象
    constructor(element: HTMLDivElement | HTMLCanvasElement) {
        // this.figTab?.clear();
        this.figTab = echarts.init(element);
        setTimeout(() => {
            this.figTab?.resize();
        }, 100);
    }
    //设置图表数据
    private setFigTab(option: any) {
        // this.figTab?.clear()
        // console.log("this.figTab", this.figTab)
        this.figTab?.setOption(option);
        return this;
    }
    /**生成余额历史记录 */
    static addBalanceHistory(ary: DayData[]) {
        YTab.list = ary;

        if (ary.length == 0) {
            console.log("没有数据");
            return;
        }
        let referenceObject = ary[ary.length - 1].position;
        if (referenceObject.length == 0) {
            console.log("没有数据");
            return;
        }

        // const total = referenceObject.reduce((a,b)=>a+b.usd, 0);
        // console.error(total)

        //@ts-ignore

        //设置x轴线时间
        BalanceHistory.xAxis[0].data = ary.map(item => new Date(item.timestamp).toLocaleDateString());
        //@ts-ignore
        //设置标题点
        BalanceHistory.legend.data = referenceObject.map(item => item.symbol);
        BalanceHistory.series = [];
        let keys = BalanceHistory?.legend?.data || [];

        console.log("----ok----");

        // let minNav = Math.min(keys.length, 6);
        for (let t = 0; t < keys.length; t++) {
            let data = ary.map(item => {
                item.position.sort((a, b) => b.usd - a.usd);
                let val = item.position.find(i => i.symbol == keys[t]);
                return val ? val.usd : 0;
            });
            BalanceHistory.series?.push({
                name: referenceObject[t].symbol,
                type: "line",
                stack: "Total",
                showSymbol: false,
                areaStyle: {},
                emphasis: {},
                data: data
            });
        }

        // console.log("yzt图表数据", BalanceHistory);
        Kfig.formatDate(3);
        (BalanceHistory as any).xAxis.boundaryGap = false;
        //数据时间搓小到大排序
        (BalanceHistory as any).xAxis.data = ary.map(item => new Date(item.timestamp).toLocaleDateString());
        kfig = new Kfig(document.getElementById("y_chart") as HTMLDivElement);
        kfig!.setFigTab(BalanceHistory);
    }
    /**截取指定第几个之后作为其它 */
    static formatDate(idx: number = 0) {
        if (BalanceHistory.legend!.data!.length > idx) {
            const otherDate: Array<any> = BalanceHistory.series
                ?.splice(idx)
                .map(item => item.data)
                .flat(1)!;
            const other = BalanceHistory.legend!.data!.splice(idx);
            // console.log("yzt__截取后的数据", otherDate, other);
            let obj = {
                areaStyle: {},
                data: otherDate,
                name: "other",
                showSymbol: false,
                type: "line"
            };
            BalanceHistory.legend?.data?.push(obj.name);
            BalanceHistory.series?.push(obj);
        }
    }
}

export { YTab, Kfig, DownType, kfig, lodding };
